import {
  registerMicroApps,
  start,
  addGlobalUncaughtErrorHandler,
  setDefaultMountApp,
  runAfterFirstMounted,
  prefetchApps
} from 'qiankun'
import store from './store'
import { whiteList } from './whiteList'
import { cloneDeep } from 'lodash'
import { Subject } from 'rxjs'
export const subject = new Subject()
let apps

/**
 * @description 这部分主要是生成注册表并调用qiankun方法的逻辑
 */

/**
 * 注入的生命周期钩子
 */
// 防止二次加载flag
let hasLoaded = false
export const hooks = {
  beforeLoad: [
    app => {
      console.log('beforeload')
      // store.commit("sys/SET_GLOBAL_LOADING", true);
    }
  ],
  beforeMount: [
    app => {
      console.log('beforemount')
      // store.commit('sys/SET_MENU', store.state.sys.rule[app.props.rules].children)
    }
  ],
  afterMount: [
    app => {
      console.log(app, 'mount')
      subject.next({
        type: 'parent',
        payload: {
          registApp: store.state.sys.registApp
        }
      })
      store.commit('sys/SET_BASE_ROUTE', app.props.rules)
      store.commit('sys/SET_GLOBAL_LOADING', false)
    }
  ],
  afterUnmount: [
    app => {
      console.log('afterUnmount')
      store.commit('sys/SET_CHILD_CLIENT_ID', '')
      store.commit('sys/SET_COPY_RIGHT', {})
    }
  ]
}
/**
 * 生成应用注册表方法
 * @description 拿到iam服务资源的内容生成对应的注册表,并且启动乾坤
 *
 */
export async function generateRegistry(routes, vue, plugins) {
  // 通知基座当前的子应用是什么
  subject.subscribe(async({ type, payload: { clientId, copyRight }}) => {
    if (type === 'child') {
      store.commit('sys/SET_CHILD_CLIENT_ID', clientId)
      // store.dispatch('sys/getMenu')
      // store.dispatch('sys/getAuth')

      store.commit('sys/SET_COPY_RIGHT', copyRight || {})
    }
  })
  if (hasLoaded) return
  routes = routes.filter(v => {
    if (v.smallFront) {
      if (v.code.endsWith('-reg')) {
        v.code = v.code.split('-reg')[0]
        v.name = v.name.split('-reg')[0]
      }
    }
    return v.smallFront
  })
  if (typeof FRONT_CONFIG !== 'undefined' && FRONT_CONFIG.mock) {
    routes.forEach(r => {
      if (FRONT_CONFIG.mockData.url[r.code]) {
        r.remark = FRONT_CONFIG.mockData.url[r.code]
      }
    })
  }
  const getActiveRule = hash => location => location.hash.startsWith(hash)
  store.commit('sys/SET_TOP_BANNER', routes)
  apps = routes.map(v => {
    return {
      name: v.code,
      entry: v.remark,
      container: v.smallFront,
      activeRule: getActiveRule(`#${v.resUrl}`),
      props: {
        container: document.querySelector(v.smallFront),
        kc: cloneDeep(vue.$keycloak),
        userInfo: cloneDeep(vue.$userInfo),
        state: cloneDeep(store.state),
        subject,
        appName: v.name,
        userOrgs: store.state.sys.userOrgs,
        orgs: store.state.sys.orgs,
        authList: store.state.sys.authList,
        currentOrgs: store.state.sys.currentOrgs, // 当前选中的公司下的组织
        currentUserOrgs: store.state.sys.currentUserOrgs, // 当前选中公司下的组织权限
        currentCompany: store.state.sys.currentCompany, // 当前选中的公司
        indexOrgs: store.state.sys.indexOrgs,
        rules: v.resUrl // 传给子应用并且在启动时通知基座
      }
    }
  })
  console.log(apps, 'aa')
  registerMicroApps(apps, hooks)

  start({
    sandbox: {
      strictStyleIsolation: false,
      experimentalStyleIsolation: true
    },
    prefetch: false
  })
  runAfterFirstMounted(() => {
    const names = ['overviewManage', 'product-index']
    const prefetcs = []
    apps.map(v => {
      if (names.includes(v.name)) {
        prefetcs.push({
          name: v.name,
          entry: v.entry
        })
      }
    })
    if (prefetcs.length > 0) {
      prefetchApps(prefetcs)
    }
  })
  if (
    ![...store.state.sys.pathList, ...whiteList].includes(
      window.location.hash.split('#')[1].split('?')[0]
    )
  ) {
    if (store.state.sys.dashBoardRule) {
      setDefaultMountApp('#' + store.state.sys.dashBoardRule)
    }
  }

  // setDefaultMountApp(`#${routes[0].resUrl}`)
  addGlobalUncaughtErrorHandler(e => {
    console.log(e)
    let hash = window.location.hash
    hash = hash.slice(1)
    const path = `/${hash.split('/')[1]}`
    // store.commit('sys/SET_MENU', store.state.sys.rule[path].children)
  })
  hasLoaded = true
}
